package com.baocaiqiche.dev.taoforandroid;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

public class ImagesActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_images);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        final ImageAdapter imageAdapter = new ImageAdapter(this);
        recyclerView.setAdapter(imageAdapter);

        HttpUtils mHttpUtils = new HttpUtils();
        mHttpUtils.getRequest("http://dev.baicaiqiche.com:8000/qiniu/listforjson", new HttpUtils.StringCallBack() {
            @Override
            public void onFailure(Request request, IOException e) {
                Toast.makeText(ImagesActivity.this,"获取图片数据失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) throws IOException {

                ArrayList<String> urlList = new ArrayList<String>();

                try {
                    JSONArray jsonArray = new JSONArray(response);
                    for (int i = 0 ; i < jsonArray.length() ; i++){
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        urlList.add(jsonObject.getString("url"));
                    }

                    imageAdapter.setDatas(urlList);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        imageAdapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ArrayList<String> imgList = imageAdapter.getDatas();
                String url = imgList.get(position);
                Intent intent = new Intent(ImagesActivity.this,ShowImageActivity.class);
                intent.putExtra("url",url);
                startActivity(intent);
            }
        });

    }

}
